import React, { Component } from 'react';

import { StyleSheet, Text, View ,Image,ImageBackground,Animated,Easing,TouchableOpacity,ScrollView,Slider} from 'react-native';
import Sound from 'react-native-sound'
import {Icon,Toast} from '@ant-design/react-native'
import musicList from '../qqmusic/musicList.js'
import AsyncStorage from "@react-native-community/async-storage";
import moment from "moment";





let isclick = true
let isclickDsq = null
let isGcTZ = 0
let isGUNdong = false
let isGUNdsq = null
export default class Yyxq extends Component {
    static navigationOptions =  ({ navigation }) =>({
        title: navigation.state.params.item.name,
        header:null
    });
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            volume: 0.5,
            seconds: 0, //秒数
            totalMin: '', //总分钟
            totalSec: '', //总分钟秒数
            nowMin: 0, //当前分钟
            nowSec: 0, //当前秒钟
            maximumValue: 100, //滑块最大值
            isPlay:false,
            fadeAnim:new Animated.Value(0),
            showLrc:true,
            curIndex:0,
            sjbf:false//随机播,
        };
        this.isPlay = false


    }

    async componentDidMount()
    {
        this._loadingMic()
    }
    componentWillMount(){


    }
    componentWillUnmount(){
        this.time && clearTimeout(this.time);
    }

    _loadingMic(){
        this.isPlay = true
        let cur = this.props.navigation.state.params.item
        if(global.curMusic){
            this._stop()
        }

        if(!global.isjinru){
            global.curMusic = new Sound(cur.src,(error)=>{
                if(error){
                    alert("播放失败。");
                    return
                }

            });

            global.curMusicName = cur.name
            setTimeout(()=>{
                this._play()
                let totalTime = global.curMusic.getDuration();
                totalTime = Math.ceil(totalTime);
                let totalMin = parseInt(totalTime/60); //总分钟数
                let totalSec = totalTime - totalMin * 60; //秒钟数并判断前缀是否 + '0'
                totalSec = totalSec > 9 ? totalSec : '0' + totalSec;
                this.setState({
                    totalMin,
                    totalSec,
                    maximumValue: totalTime,
                })

            },1000)

        }else {
            global.isjinru = false
            this.setState({isPlay:true})
            let totalTime = global.curMusic.getDuration();
            totalTime = Math.ceil(totalTime);
            let totalMin = parseInt(totalTime/60); //总分钟数
            let totalSec = totalTime - totalMin * 60; //秒钟数并判断前缀是否 + '0'
            totalSec = totalSec > 9 ? totalSec : '0' + totalSec;
            this.setState({
                totalMin,
                totalSec,
                maximumValue: totalTime,
            })
            global.curMusic.setCurrentTime(global.seconds)
            global.curMusic.play((cg=>{
                if(cg){
                    this._next()
                }

            }));
            this.time = setInterval(() => {
                global.curMusic.getCurrentTime(seconds => {
                    this.isHeiht(seconds)
                    seconds = Math.ceil(seconds);
                    this._getNowTime(seconds)
                })
            },100)
        }

    }
    _addVolume = () => {
        let volume = this.state.volume;
        volume += 0.1;
        volume = parseFloat(volume).toFixed(1) * 1;
        if(volume > 1){
            return alert('目前已经是最大音量');
        }
        this.setState({volume: volume});
        global.curMusic.setVolume(volume);
    }
    // 声音-
    _reduceVolume = () => {
        let volume = this.state.volume;
        volume -= 0.1;
        volume = parseFloat(volume).toFixed(1) * 1;
        if(volume < 0){
            return alert('当前为静音');
        }
        this.setState({volume: volume});
        global.curMusic.setVolume(volume);
    }
    // 播放
    _play = () => {
        if(global.curMusic){
            this.isPlay = true
            this.setState({isPlay:true})
            if(!global.isjinru){
                global.curMusic.play((cg=>{
                    if(cg){
                        this._next()
                    }

                }));
            }
            if(this.myScrollView){
                this.time = setInterval(() => {
                    global.curMusic.getCurrentTime(seconds => {
                        this.isHeiht(seconds)
                        seconds = Math.ceil(seconds);
                        this._getNowTime(seconds)
                    })
                },100)
            }



        }else {
            alert('请选择歌曲')
        }

    }
    // 暂停
    _pause = () => {
        this.isPlay = false
        this.setState({isPlay:false})
        clearInterval(this.time);
        global.curMusic.pause();
    }
    // 停止
    _stop = () => {
        this.isPlay = false
        this.setState({isPlay:false})
        clearInterval(this.time);
        this.setState({
            nowMin: 0,
            nowSec: 0,
            seconds: 0,
        })

        global.curMusic.stop();
    }
    _pd(){
        clearTimeout(isclickDsq)
        isclick = false
        isclickDsq = setTimeout(()=>{
            isclick = true
        },200)
    }
    //下一首
    _shang(){
        if(isclick){
            this._stop()
            let nub = musicList.findIndex((item,index)=>{
                return  this.props.navigation.state.params.item.name== item.name
            })

            if(nub == 0){
                this.props.navigation.state.params.item = musicList[musicList.length - 1]
            }else {
                this.props.navigation.state.params.item = musicList[nub-1]
            }
            setTimeout(()=>{
                this._loadingMic()
            },50)
            this._pd()
        }


    }
    _next(){

        if(isclick){
            this._stop()

            if(this.state.sjbf){

                let num = Math.floor(Math.random()*(musicList.length-1))
                this.props.navigation.state.params.item = musicList[num]
            }else {
                let nub = musicList.findIndex((item,index)=>{
                    return  this.props.navigation.state.params.item.name== item.name
                })
                if((nub+1)>= musicList.length){
                    this.props.navigation.state.params.item = musicList[0]
                }else {
                    this.props.navigation.state.params.item = musicList[nub+1]
                }

            }

            setTimeout(()=>{
                this._loadingMic()
            },100)

            this._pd()
        }


    }

    _getNowTime = (seconds) => {
        let nowMin = this.state.nowMin,
            nowSec = this.state.nowSec;
        if(seconds >= 60){
            nowMin = parseInt(seconds/60); //当前分钟数
            nowSec = seconds - nowMin * 60;
            nowSec = nowSec < 10 ? '0' + nowSec : nowSec;
        }else{
            nowSec = seconds < 10 ? '0' + seconds : seconds;
        }
        this.setState({
            nowMin,
            nowSec,
            seconds
        })
    }
    dPlay(){


        this.isPlay?this._pause():this._play()
    }
    isHeiht(zhi){

        let lrc = this.props.navigation.state.params.item.lrc
        let cc= lrc.findIndex(item=>item.time>zhi)


        if(isGcTZ !== cc && !isGUNdong){
            this.myScrollView.scrollTo({ x: 0, y: (cc*25)-150, animated: true});
            isGcTZ = cc
        }


        this.setState({curIndex:cc})
    }
    _quehuanbof(){
        if(this.state.sjbf){
            //alert('已切换到顺序播放')
            this.setState({
                sjbf: false
            })
        }else {
           // alert('已切换到随机播放')
            this.setState({
                sjbf: true
            })
        }
    }
    render() {
        let time = this.state;
        let item1 = this.props.navigation.state.params.item
        return (
            <ImageBackground  style={{ flex: 1,flexDirection: 'column'}} source={require('../assets/images/mbbj.jpg')}>
                <View style={{flex: 1, flexDirection: 'row',height: 50}}>
                    <View style={{width: '15%', height: 50,position:'absolute',zIndex:999}} ><Icon style={{color:'#fff',lineHeight:50,textAlign:'center'}} onPress={()=>{
                        return this.props.navigation.goBack()
                    }}  name="down" size="md" color="#fff" /></View>
                    <View style={{ width: '100%',height: 50,color:'#fff'}} ><Text style={{color:'#fff',lineHeight:50,textAlign:'center',fontSize:20}}>{item1.name}</Text></View>
                </View>
                <View style={{
                    position:'absolute',top:60,left:0,width:'100%',
                    flex: 1,
                    flexDirection: 'row',
                    alignItems:'center',
                    justifyContent:'center'
                }} >

                    <ScrollView scrollEventThrottle={3} onScrollBeginDrag={()=>{
                        isGUNdong = true
                    }}
                                onScrollEndDrag={()=>{
                                    clearTimeout(isGUNdsq)
                                    isGUNdsq =  setTimeout(()=>{
                                        isGUNdong = false
                                    },4000)
                                }}
                                style={{
                                    // 尺寸
                                    width:100,
                                    height:450,
                                    display:time.showLrc?'flex':'none'
                                }} ref={(view) => { this.myScrollView = view; }}>
                        {

                            item1.lrc.map((item, index) => {
                                return <Text key={index} style={{color:time.curIndex<=index?'#fff':'#ff0',textAlign:'center',lineHeight:25,fontSize: 15}}>{item.ci}</Text>
                            })
                        }
                    </ScrollView>
                </View>
                <View style={{position:'absolute',bottom:0,left:0,width:'90%', marginLeft :'5%',marginRight:'5%',marginBottom:'15%'}} >
                    <View style={{flex: 1, flexDirection: 'row',height: 40}}>
                        <View style={{width: '10%', height: 40}} ><Text style={{color:'#fff',lineHeight:40,textAlign:'center'}}>{time.nowMin}:{time.nowSec}</Text></View><View style={{ width: '80%',height: 40}} >
                            <View style={{ width: '90%',height: 40, marginLeft :'5%',marginRight:'5%',paddingTop:10}} >

                                <Slider
                                    // disabled //禁止滑动
                                    maximumTrackTintColor={'#ccc'} //右侧轨道的颜色
                                    minimumTrackTintColor={'skyblue'} //左侧轨道的颜色
                                    maximumValue={this.state.maximumValue} //滑块最大值
                                    minimumValue={0} //滑块最小值
                                    thumbTintColor={'#fe2'}
                                    value={this.state.seconds}
                                    onSlidingComplete={(value)=>{ //用户完成更改值时调用的回调（例如，当滑块被释放时）
                                        value = parseInt(value);
                                        this._getNowTime(value)
                                        // 设置播放时间
                                        global.curMusic.setCurrentTime(value);
                                    }}
                                /></View></View>
                        <View style={{ width: '10%',height: 40}}><Text style={{color:'#fff',lineHeight:40,textAlign:'center'}}>{time.totalMin}:{time.totalSec}</Text></View>
                    </View>

                    {/*                <Text>当前音量: {this.state.volume}</Text>
                <Text onPress={this._addVolume}>声音+</Text>
                <Text onPress={this._reduceVolume}>声音-</Text>*/}

                    <View style={{flex: 1, flexDirection: 'row',height: 40}}>
                        <View style={{width: '25%', height: 60}} ><Icon style={{color:'#fff',lineHeight:50,textAlign:'center'}}  onPress={ async ()=>{
                            try {
                                let result =   await AsyncStorage.getItem('@isJh')
                                if(!result){
                                    let today =  await AsyncStorage.getItem('@today')
                                    if(moment().isBefore(today)){
                                        this._quehuanbof()
                                    }else {
                                        alert('请激活播放器使用该功能！')
                                    }
                                }else {
                                    this._quehuanbof()
                                }
                            } catch (e) {
                                // saving error
                            }

                        }}  name={time.sjbf?'fullscreen-exit':"bars"} size="lg" color="#fff" /><Text style={{color:'#fff',lineHeight:14,textAlign:'center'}}>{time.sjbf?'随机':"顺序"}</Text></View>
                        <View style={{width: '25%', height: 60}} ><Icon style={{color:'#fff',lineHeight:50,textAlign:'center'}} onPress={async()=>{
                            try {
                                let result =   await AsyncStorage.getItem('@isJh')
                                if(!result){
                                    let today =  await AsyncStorage.getItem('@today')
                                    if(moment().isBefore(today)){
                                        this._shang()
                                    }else {
                                        alert('请激活播放器使用该功能！')
                                    }

                                }else {
                                    this._shang()
                                }
                            } catch (e) {
                                // saving error
                            }

                        }}  name="left-circle" size="lg" color="#fff" /></View>
                        <View style={{ width: '25%',height: 40}} ><Icon style={{color:'#fff',lineHeight:50,textAlign:'center'}} onPress={()=>this.dPlay()} name={time.isPlay?"pause-circle":"play-circle"} size="lg" color="#fff" /></View>
                        <View style={{ width: '25%',height: 40}}><Icon style={{color:'#fff',lineHeight:50,textAlign:'center'}} onPress={ async ()=>{
                            try {
                                let result =   await AsyncStorage.getItem('@isJh')
                                if(!result){
                                    let today =  await AsyncStorage.getItem('@today')
                                    if(moment().isBefore(today)){
                                        this._next()
                                    }else {
                                        alert('请激活播放器使用该功能！')
                                    }
                                }else {
                                    return this._next()
                                }
                            } catch (e) {
                                // saving error
                            }

                        }}  name="right-circle" size="lg" color="#fff" /></View>
                    </View>
                    {/*             <Text onPress={this._play}>播放</Text>
                <Text onPress={this._pause}>暂停</Text>
                <Text onPress={this._stop}>停止</Text>*/}
                    {/*    <Text onPress={()=>{
                        this.setState({showLrc:!time.showLrc})}}>切换歌词</Text>*/}
                </View>
            </ImageBackground>
        );
    }

}


const styles = StyleSheet.create({
    loadingBox: { // Loading居中
        flex:1,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'rgba(0, 0, 0, 0.5)', // 半透明
    }
});
